package cn.chiship.sdk.core.encryption;

import cn.chiship.sdk.core.encryption.rsa.RsaEncrypt;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;

/**
 * 票据
 *
 * @author lj
 */
public class ProofUtil {

	private ProofUtil() {

	}

	/**
	 * 生成票据 appId 雪花算法 appKey UUID随机生成 signKey UUID随机串+appKey+appId得到字符串进行MD5加密，截取2，9字符
	 * appSecret appId+appKey+signKey 得到字符串 进行2次MD5加密
	 * @return 票据JSON
	 */
	public static JSONObject generateProof() {
		JSONObject proofJson = new JSONObject();
		String appId = SnowflakeIdUtil.generateStrId();
		String appKey = RandomUtil.uuidLowerCase();
		String signKey = Md5Util.md5(RandomUtil.uuidLowerCase() + appKey + appId).substring(2, 9);
		String appSecret = Md5Util.md5(Md5Util.md5(appId + appKey + signKey));
		String[] keys = RsaEncrypt.genKeyPair();
		String publicKey = keys[0];
		String privateKey = keys[1];
		proofJson.put("appId", appId);
		proofJson.put("appKey", appKey);
		proofJson.put("appSecret", appSecret);
		proofJson.put("signKey", signKey);
		proofJson.put("privateKey", privateKey);
		proofJson.put("publicKey", publicKey);
		return proofJson;
	}

	/**
	 * 校验appId、appKey、appSecret正确性
	 * @param appId
	 * @param appKey
	 * @param signKey
	 * @param appSecret
	 * @return 验证结果
	 */
	public static boolean verifyAppSecret(String appId, String appKey, String signKey, String appSecret) {
		return appSecret.equals(Md5Util.md5(Md5Util.md5(appId + appKey + signKey)));
	}

}
